import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Form , RouteLayout , ListEditable } from 'weaver-mobile-page';
import { Icon, Result , Tools , Modal , Bubble} from 'weaver-mobile';
import { toJS } from 'mobx';
import MeetingUtil from '../../../util/meetingUtil';
const ButtonGroup = RouteLayout.ButtonGroup;

const getLabel = Tools.getLabel;

const List = ListEditable.List

@inject('viewMeetingStore')
@withRouter
@observer
class Decisoin extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        disabled:false,
      };
    }

    componentWillMount(){
      this.setState({disabled:false})
      if(this.props.location.pathname === '/calendar/detail/decisionData'){
        const { setState } = this.props.viewMeetingStore;
        setState({isView:'1',renderToDecision:false})
      }
    }
    
    componentDidMount() {
      const { getDecisionForm , setState  , getDecisionList, getDecisionCondition ,meetingId,type} = this.props.viewMeetingStore;
      //考虑到刷新的时候
      let typeTemp = type?type:sessionStorage.getItem('type')
      let meetingIdTemp = meetingId?meetingId:sessionStorage.getItem('meetingId')
      setState({type:typeTemp,meetingId:meetingIdTemp})
      //获得决议基本信息表单
      getDecisionForm();
      getDecisionCondition();
      getDecisionList();
    }

    componentWillReceiveProps (nextProps) {
      if(nextProps.location.pathname === '/calendar/detail/decisionData'){
        const { setState } = this.props.viewMeetingStore;
        setState({isView:'1'})
      }
    }

    componentWillUnmount () {
      
    }

    getFields = ()=>{
      const { decisionForm , decisionList , decisionConditions ,isView ,decisionData,decisionInitialData,
        decisionistEditable,setDecisionData ,setState} = this.props.viewMeetingStore;
      let tempIsView = isView?isView:sessionStorage.getItem('decisionIsView')
      setState({isView:tempIsView})
      const { isInit ,conditioninfo } = decisionForm;
      const groups = [];
      isInit && conditioninfo.length!==0 && conditioninfo.forEach((group) => {
        const fields = [];
        if(group.isDecisionDetail === true){
          if(decisionList.data.length > 0 && (tempIsView==='1')){
            fields.push(<List
              className={'decision-preview'}
              store={decisionList}
              onRowSelect = {()=>{return;}}
              onRowClick = {()=>{return;}}
              conditions = {decisionConditions}
              />
              )
          }else if(tempIsView==='0'){
            fields.push(<ListEditable
              store={decisionistEditable}
              rowKey="id"
              data={decisionData}
              initData={decisionInitialData}
              conditions = {decisionConditions}
              showSN = {false}
              onChange={(newData) => {
                setDecisionData(newData)
              }}
              willDelete={newData => new Promise((resolve) => {
                Modal.alert('确定要删除吗？', '', [
                  { text: '取消', onPress: () => resolve(false) },
                  {
                    text: '确定',
                    onPress: () => {
                      resolve(newData);
                    },
                  },
                ]);
              })}
              />
              )
          }else{
            fields.push(<div className={'lastlySignList-nodata'}>
            <Result
              img={<Icon type="no-data" />}
              message={getLabel(83553, '暂无数据')}
            />
          </div>
              )
          }
          
        }else{
          group.items.forEach((field) => {
            fields.push(<Form.Item
              key={field.domkey.join('__')}
              form={decisionForm}
              fieldConfig={field}
              onChange={decisionForm.onChange}
            />);
          })
        }
        
        groups.push(
          // 分组
          <div className='fold-group' key={group.title}>
            <div className='fold-title' onClick={() => {this.handleToggle(group.title, !group.show)}}>
              {group.title}
              <Icon className="flod-icon" type={group.show ? 'up' : 'down'} />
            </div>
            <div className={`${group.show ? 'show' : 'hide'}`}>
              {fields}
            </div>
          </div>
        )
      })
      return groups;
    }

    handleToggle = (...arg) => {
      const {groupToggleDecisionForm} = this.props.viewMeetingStore;
      groupToggleDecisionForm(...arg);
    }


    render() {
      const { isView,type} = this.props.viewMeetingStore;
      const decisionHeight = this.getHeight();
      let baseBtns = this.getBtns();
      return (
        <div style={{height:type==='view'?decisionHeight:'100%'}}>
        <div className={'decision-data-contain'} >
          {this.getFields()}
        </div>
        {isView !== '1' &&<div className={'decision-button'}><ButtonGroup data={baseBtns}/></div>}
        </div>
      )
    }

    getHeight = () => {
      return document.body.clientHeight - MeetingUtil.getTabHeight() - MeetingUtil.getButtonHeight();
    }

    setOnLoading = (flg=false)=> {
      const { setState } = this.props.viewMeetingStore;
      setState({onLoading:flg})
    }

    handleSubmitDecisoin = (type='edit')=>{
      this.setState({disabled:true})
      const { decisionForm ,editDecision,submitDecision,decisionistEditable,decisionData} = this.props.viewMeetingStore;
      let { allDecisionData } = this.props.viewMeetingStore;
      const valuesTemp = decisionForm.formParams
      allDecisionData = {...allDecisionData,...valuesTemp};
      let canChange = true;

      //检验会议决议的必填信息
      let validResult = decisionForm.doValidate();
      if(!validResult.pass){
        this.setState({disabled:false});
        this.setOnLoading();
        return;
      }

      //校验
      decisionistEditable.doValidate(
        (pass, id, result) => {
          if (!pass) {
            this.setState({disabled:false})
            canChange = false
            // 如果校验失败
            const form = decisionistEditable.formList[id]; // 获取报错的form
            const { message, domkey } = result;
            decisionistEditable.setState({ editingKey: id });
            this.props.history.push(decisionistEditable.pathToEditor); // 跳转到编辑页面
            setTimeout(() => { // 等待页面渲染
              Bubble.error(message, 1, { top: '50%' }); // 错误提示
              form.focusField(domkey); // 定位到错误项
            }, 200);
            return;
          }
        },
      )
      if(canChange) {
        let decisionDataIndex = 0;
        for(let v in toJS(decisionData)) {
          decisionDataIndex ++;
          if(decisionData[v] && (decisionData[v].begindate >= decisionData[v].enddate)) {
            canChange = false;
            let id = decisionData[v].id;
            const form = decisionistEditable.formList[id];
            decisionistEditable.setState({ editingKey: id });
            this.props.history.push(decisionistEditable.pathToEditor); 
            this.setState({disabled:false});
            Bubble.error(getLabel('520110','第${num}行决议开始时间应小于结束时间。').replace('${num}', decisionDataIndex), 1.5, { top: '50%' }); // 错误提示
            break;
          }
        }
      }

      if(canChange){
        //计算决议任务详情
        const formList = decisionistEditable.formList;
        allDecisionData = {...allDecisionData,decisionrows:Object.keys(formList).length}
        let eachvalue = {};
        decisionData.forEach((val1,index)=>{
          Object.keys(val1).forEach((key2,value)=>{
            eachvalue[`${key2}_${index+1}`]=val1[key2]
          })
        })
        allDecisionData = {...allDecisionData,...eachvalue}
        if(type==='edit'){
          editDecision(allDecisionData,this.goBack)
        }else{
          submitDecision(allDecisionData,this.goBack)
        }

      }
      
    }

    getBtns = (compo='button')=>{
      let baseBtns = [];
      baseBtns=[
        {
          key: 'add',
          text: getLabel(30986, '保存'),
          disabled:this.state.disabled,
          onClick: () => {this.handleSubmitDecisoin('edit')},
        },
        {
          key: 'submit',
          text: getLabel(725, '提交'),
          disabled:this.state.disabled,
          type: 'primary',
          onClick: () => {this.handleSubmitDecisoin('submit')},
        },
      ]
      return baseBtns;
    }

    goBack = ()=>{
      let {getPreview, meetingId, setState } = this.props.viewMeetingStore;
      //加一个callback作用是编辑复制的时候调整会议室和自定义会议地点的必填非必填
      let params = {};
      params.meetingid = meetingId
      getPreview({...params})
      // this.props.history.goBack()
      this.props.history.push('/calendar/detail/decisionData')
    }
}

export default Decisoin;